package com.cjh.admin.config.shiro;

import com.cjh.admin.utils.JwtUtil;
import com.cjh.common.entity.User;
import com.cjh.common.service.PermissionService;
import com.cjh.common.service.RoleService;
import com.cjh.common.service.UserService;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Set;

@Component
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Autowired
    RoleService roleService;
    @Autowired
    PermissionService permissionService;
    @Override
    //获得自己定义的token
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String)principalCollection.iterator().next();
        Set<String> roleNames = roleService.getAllRoleNamesByUsername(username);
        Set<String> permission = permissionService.getAllPermissionByUsername(username);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roleNames);
        info.setStringPermissions(permission);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        JwtToken jwtToken = (JwtToken)token;
        String jwt = (String)jwtToken.getPrincipal();
        Claims claims = null;
        claims = JwtUtil.parseJWT(jwt);
        String username = claims.getId();
        User user = userService.getUserByUserName(username);
        if( user == null ){
            return null;
        }
        return new SimpleAuthenticationInfo(username,user.getPassword(),getName());
    }
}
